package com.maodou.android.ui.page.account

import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.asPaddingValues
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.navigationBars
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.outlined.KeyboardArrowLeft
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ScrollableTabRow
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.shadow
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.compose.LocalLifecycleOwner
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.hjq.permissions.permission.PermissionLists
import com.maodou.android.R
import com.maodou.android.automator.AppAccessibilityService
import com.maodou.android.data.model.ProxyCheckResp
import com.maodou.android.ui.page.AccountDetailKey
import com.maodou.android.ui.page.EditAccountKey
import com.maodou.android.ui.page.Verify2faKey
import com.maodou.android.ui.page.home.ActionBottomItem
import com.maodou.android.utils.PublicUtils.countryNameZh
import com.maodou.android.viewmodel.account.AccountViewModel
import com.maodou.core.navigation.Navigator3
import com.maodou.core.ui.components.ActionBar
import com.maodou.core.ui.components.AppDivider
import com.maodou.core.ui.components.AppText
import com.maodou.core.ui.components.HSpacer
import com.maodou.core.ui.components.TitleAlignment
import com.maodou.core.ui.components.VSpacer
import com.maodou.core.ui.components.debouncedClickable
import com.maodou.core.utils.JsonUtils
import com.maodou.core.utils.Logger
import com.maodou.core.utils.permission.PermissionUtils

/**
 * @Author Xing
 * @CreateTime 2025年09月22日
 * @Description 账号详情
 */
@Composable
fun AccountDetailsScreen(key: AccountDetailKey, viewModel: AccountViewModel = hiltViewModel()) {
    val uiState by viewModel.uiState.collectAsStateWithLifecycle()
    val navigationBarHeight = WindowInsets.navigationBars.asPaddingValues().calculateBottomPadding()
    val context = LocalContext.current
    var account by remember { mutableStateOf(key.account) }
    var tabs by remember { mutableStateOf(if(account?.proxyChannel.isNullOrEmpty()) arrayListOf("账号信息") else arrayListOf("账号信息","代理信息")) }
    var selectedTab by remember { mutableIntStateOf(0) }
    val lifecycleOwner = LocalLifecycleOwner.current
    DisposableEffect(lifecycleOwner) {
        val observer = LifecycleEventObserver { _, event ->
            when (event) {
                Lifecycle.Event.ON_RESUME -> {
                   viewModel.getAccountById("${account?.accountID}") {
                       account = it
                       tabs = if(account?.proxyChannel.isNullOrEmpty()) arrayListOf("账号信息") else arrayListOf("账号信息","代理信息")
                       if(tabs.size == 1) selectedTab = 0
                   }
                }
                else -> {}
            }
        }
        lifecycleOwner.lifecycle.addObserver(observer)
        onDispose {
            lifecycleOwner.lifecycle.removeObserver(observer)
        }
    }

    Column(modifier = Modifier.fillMaxSize()) {
        ActionBar(
            title = "账号详情",
            modifier = Modifier.fillMaxWidth(),
            navigationIcon = Icons.AutoMirrored.Outlined.KeyboardArrowLeft,
            onNavigationClick = { Navigator3.pop() },
            backgroundColor = Color.Transparent,
            contentColor = MaterialTheme.colorScheme.onSurface,
            titleAlignment = TitleAlignment.Center,
        )

        Row (modifier = Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
            if(tabs.size > 1) ScrollableTabRow(
                selectedTabIndex = selectedTab,
                edgePadding = 0.dp,
                divider = {},
                containerColor = Color.Transparent,
                contentColor = Color.Transparent,
                modifier = Modifier.weight(1f),
                indicator = { tabPositions ->
                    val indicatorWidth = 26.dp
                    val indicatorHeight = 4.dp
                    val current = tabPositions[selectedTab]
                    val indicatorOffsetX = current.left + (current.width - indicatorWidth) / 2
                    Box(Modifier.fillMaxSize()) {
                        Box(
                            Modifier
                                .align(Alignment.BottomStart)
                                .offset(x = indicatorOffsetX)
                                .width(indicatorWidth)
                                .height(indicatorHeight)
                                .clip(RoundedCornerShape(50))
                                .background(MaterialTheme.colorScheme.primary)
                        )
                    }
                }
            ) {
                tabs.forEachIndexed { index, title ->
                    val selected = selectedTab == index
                    Box(
                        contentAlignment = Alignment.Center,
                        modifier = Modifier
                            .widthIn(min = 60.dp)
                            .height(40.dp).debouncedClickable {
                                selectedTab = index
                            }
                    ){
                        AppText(
                            text = title,
                            color = if (selected) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurfaceVariant,
                            style = TextStyle(
                                fontSize = if (selected) 16.sp else 14.sp,
                                fontWeight = if (selected) FontWeight.Bold else FontWeight.Medium,
                            ),
                            modifier = Modifier.padding(horizontal = 12.dp)
                        )
                    }
                }
            }

            if(selectedTab == 1) Button(
                onClick = {
                    PermissionUtils.requestVpnServicePermissions {
                        //todo 获取vpn权限后开始检测
                        viewModel.proxyCheck(
                            channel = "${account?.proxyChannel}",
                            protocol = "${account?.proxyType}",
                            host = "${account?.proxyHost}",
                            port = "${account?.proxyPort}",
                            username = "${account?.proxyAccount}",
                            password = "${account?.proxyPassword}",
                        )
                    }
                },
                border = BorderStroke(1.dp, color = if(uiState.isCheckProxy) Color.Transparent else MaterialTheme.colorScheme.primary),
                colors = ButtonDefaults.buttonColors(
                    containerColor = Color.White,
                    contentColor = Color.White
                ),

                contentPadding = PaddingValues(1.dp),
                enabled = !uiState.isCheckProxy,
                modifier = Modifier
                    .height(20.dp)
                    .width(56.dp),
                shape = RoundedCornerShape(4.dp)
            ) {
                if (uiState.isCheckProxy) {
                    CircularProgressIndicator(
                        modifier = Modifier.size(12.dp),
                        strokeWidth = 2.dp,
                        color = MaterialTheme.colorScheme.onSecondary
                    )
                    Text(
                        text = "检测中...",
                        textAlign = TextAlign.Center,
                        color = MaterialTheme.colorScheme.onSecondary,
                        fontSize = 10.sp
                    )
                } else Text(text = "代理检测", textAlign = TextAlign.Center, fontSize = 10.sp, lineHeight = 11.sp, color = MaterialTheme.colorScheme.primary)
            }

            HSpacer(16.dp)

        }

        val groupShape = RoundedCornerShape(16.dp)

        if(selectedTab == 0){
            Column(
                modifier = Modifier
                    .fillMaxWidth()
                    .weight(1f)
                    .verticalScroll(rememberScrollState())
                    .padding(horizontal = 16.dp, vertical = 12.dp)
            ) {
                if (account == null) {
                    AppText(text = "暂无账号数据")
                    return@Column
                }

                Row(
                    verticalAlignment = Alignment.CenterVertically,
                    horizontalArrangement = Arrangement.SpaceBetween,
                    modifier = Modifier.fillMaxWidth().padding(bottom = 8.dp)
                ) {
                    AppText(
                        text = "基本信息",
                        style = MaterialTheme.typography.bodySmall.copy(fontWeight = FontWeight.Bold),
                        color = MaterialTheme.colorScheme.onSurfaceVariant,
                        modifier = Modifier
                    )

                    Row(
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Box(
                            modifier = Modifier
                                .size(10.dp)
                                .clip(RoundedCornerShape(50))
                                .padding(0.dp),
                            contentAlignment = Alignment.Center
                        ) {
                            Surface(
                                color = if (account?.online == 1) Color(0xFFF2994A) else if(account?.online == 2)Color(0xFF27AE60) else Color(0xFFE74C3C),
                                shape = RoundedCornerShape(50)
                            ) { Spacer(Modifier.size(10.dp)) }
                        }
                        HSpacer(4.dp)
                        AppText(
                            text = if (account?.online == 1) "待检测" else if(account?.online == 2) "存活中" else "被封禁",
                            style = MaterialTheme.typography.bodySmall.copy(fontSize = 12.sp),
                            color = if (account?.online == 1) Color(0xFFF2994A) else if(account?.online == 2)Color(0xFF27AE60) else Color(0xFFE74C3C),
                            modifier = Modifier
                        )
                    }

                }

                Column(
                    modifier = Modifier
                        .fillMaxWidth()
                        .shadow(elevation = 1.dp, shape = groupShape)
                        .clip(groupShape)
                        .background(Color.White)
                        .padding(16.dp)
                ) {
                    Row(verticalAlignment = Alignment.CenterVertically) {
                        Row (modifier = Modifier.weight(1f), verticalAlignment = Alignment.CenterVertically) {
                            Icon(
                                painter = painterResource(id = if(account?.platform == "Instagram") R.mipmap.ic_instagram_logo else R.mipmap.ic_facebook_logo),
                                contentDescription = null,
                                tint = Color.Unspecified,
                                modifier = Modifier.size(24.dp).clip(RoundedCornerShape(6.dp))
                            )
//                        AvatarImage(
//                            model = "http://graph.facebook.com/${account.accountID}/picture?type=square",
//                            size = 40.dp
//                        )
                            HSpacer(8.dp)
                            AppText(
                                text = "平台",
                                style = MaterialTheme.typography.bodySmall,
                                color = MaterialTheme.colorScheme.onSurfaceVariant,
                                maxLines = 1,
                                overflow = TextOverflow.Ellipsis
                            )
                        }

                        AppText(
                            text = account?.platform ?: "",
                            style = MaterialTheme.typography.bodySmall,
                            color = MaterialTheme.colorScheme.onSurface
                        )
                    }
                    AppDivider(modifier = Modifier.padding(vertical = 10.dp))
                    Row(verticalAlignment = Alignment.CenterVertically) {
                        Row (modifier = Modifier.weight(1f), verticalAlignment = Alignment.CenterVertically) {
                            AppText(
                                text = "分类",
                                style = MaterialTheme.typography.bodySmall,
                                color = MaterialTheme.colorScheme.onSurfaceVariant,
                                maxLines = 1,
                                overflow = TextOverflow.Ellipsis
                            )
                        }

                        AppText(
                            text = account?.type ?: "",
                            style = MaterialTheme.typography.bodySmall,
                            color = MaterialTheme.colorScheme.onSurface
                        )
                    }
                }

                VSpacer(16.dp)

                // 账号鉴定信息
                AppText(
                    text = "账号信息",
                    style = MaterialTheme.typography.bodySmall.copy(fontWeight = FontWeight.Bold),
                    color = MaterialTheme.colorScheme.onSurfaceVariant,
                    modifier = Modifier.padding(bottom = 8.dp)
                )

                Column(
                    modifier = Modifier
                        .fillMaxWidth()
                        .shadow(elevation = 1.dp, shape = groupShape)
                        .clip(groupShape)
                        .background(Color.White)
                        .padding(horizontal = 12.dp)
                ) {
                    VSpacer(10.dp)
                    // 账号ID
                    DetailRow(label = "账号ID", value = account?.accountID ?: "", copyable = true) { copyText(context, "${account?.accountID}") }
                    if(!account?.nickname.isNullOrEmpty()){
                        AppDivider(modifier = Modifier.padding(vertical = 10.dp))
                        // 昵称/备注
                        DetailRow(label = "昵称/备注", value = account?.nickname ?: "-")
                    }

                    if(!account?.phone.isNullOrEmpty()){
                        AppDivider(modifier = Modifier.padding(vertical = 10.dp))
                        // 手机号
                        DetailRow(label = "手机号", value = account?.phone ?: "-", copyable = true) {
                            copyText(context, account?.phone ?: "")
                        }
                    }

                    if(!account?.password.isNullOrEmpty()){
                        AppDivider(modifier = Modifier.padding(vertical = 10.dp))
                        // 密码
                        DetailRow(label = "密码", value = account?.password ?: "-", copyable = !account?.password.isNullOrEmpty()) {
                            copyText(context, account?.password ?: "")
                        }
                    }

                    if(!account?.twoFa.isNullOrEmpty()){
                        AppDivider(modifier = Modifier.padding(vertical = 10.dp))
                        // 2FA
                        DetailRow(label = "2FA", value = account?.twoFa ?: "-", copyable = !account?.twoFa.isNullOrEmpty()) {
                            copyText(context, account?.twoFa ?: "")
                        }
                    }

                    if(!account?.email.isNullOrEmpty()){
                        AppDivider(modifier = Modifier.padding(vertical = 10.dp))
                        // 邮箱
                        DetailRow(label = "邮箱", value = account?.email ?: "-", copyable = true) {
                            copyText(context, account?.email ?: "")
                        }
                    }

                    if(!account?.emailPassword.isNullOrEmpty()){
                        AppDivider(modifier = Modifier.padding(vertical = 10.dp))
                        // 邮箱密码
                        DetailRow(label = "邮箱密码", value = account?.emailPassword ?: "-", copyable = !account?.emailPassword.isNullOrEmpty()) {
                            copyText(context, account?.emailPassword ?: "")
                        }
                    }

                    if(!account?.ipCountry.isNullOrEmpty()){
                        AppDivider(modifier = Modifier.padding(vertical = 10.dp))
                        // IP/国家
                        DetailRow(label = "IP/国家", value = account?.ipCountry ?: "-")
                    }

                    // Cookie
                    if(!account?.cookie.isNullOrEmpty()){
                        AppDivider(modifier = Modifier.padding(vertical = 10.dp))
                        DetailRow(label = "Cookie", value = account?.cookie ?: "-", multiLine = true, copyable = !account?.cookie.isNullOrEmpty()) {
                            copyText(context, account?.cookie ?: "")
                        }
                    }
                    VSpacer(12.dp)
                }

                VSpacer(16.dp)

            }
        } else if (selectedTab == 1){
            Column(
                modifier = Modifier
                    .fillMaxWidth()
                    .weight(1f)
                    .verticalScroll(rememberScrollState())
                    .padding(horizontal = 16.dp, vertical = 12.dp)
            ) {
                // 代理信息
//                AppText(
//                    text = "代理信息",
//                    style = MaterialTheme.typography.bodySmall.copy(fontWeight = FontWeight.Bold),
//                    color = MaterialTheme.colorScheme.onSurfaceVariant,
//                    modifier = Modifier.padding(bottom = 8.dp)
//                )

                Column(
                    modifier = Modifier
                        .fillMaxWidth()
                        .shadow(elevation = 1.dp, shape = groupShape)
                        .clip(groupShape)
                        .background(Color.White)
                        .padding(horizontal = 12.dp)
                ) {
                    VSpacer(10.dp)
                    // 代理渠道
                    DetailRow(label = "代理渠道", value = account?.proxyChannel ?: "", copyable = true) { copyText(context, "${account?.proxyChannel}") }
                    if(!account?.proxyType.isNullOrEmpty()){
                        AppDivider(modifier = Modifier.padding(vertical = 10.dp))
                        // 昵称/备注
                        DetailRow(label = "代理类型", value = account?.proxyType ?: "-")
                    }

                    if(!account?.proxyHost.isNullOrEmpty()){
                        AppDivider(modifier = Modifier.padding(vertical = 10.dp))
                        // 手机号
                        DetailRow(label = "代理主机", value = account?.proxyHost ?: "-", copyable = true) {
                            copyText(context, account?.proxyHost ?: "")
                        }
                    }

                    if(!account?.proxyPort.isNullOrEmpty()){
                        AppDivider(modifier = Modifier.padding(vertical = 10.dp))
                        // 密码
                        DetailRow(label = "代理端口", value = account?.proxyPort ?: "-", copyable = !account?.proxyPort.isNullOrEmpty()) {
                            copyText(context, account?.proxyPort ?: "")
                        }
                    }

                    if(!account?.proxyAccount.isNullOrEmpty()){
                        AppDivider(modifier = Modifier.padding(vertical = 10.dp))
                        // 2FA
                        DetailRow(label = "代理账号", value = account?.proxyAccount ?: "-", copyable = !account?.proxyAccount.isNullOrEmpty()) {
                            copyText(context, account?.proxyAccount ?: "")
                        }
                    }

                    if(!account?.proxyPassword.isNullOrEmpty()){
                        AppDivider(modifier = Modifier.padding(vertical = 10.dp))
                        // 邮箱
                        DetailRow(label = "代理密码", value = account?.proxyPassword ?: "-", copyable = true) {
                            copyText(context, account?.proxyPassword ?: "")
                        }
                    }
                    val proxyDetect = if(account?.proxyDetect?.isEmpty() == true) null else JsonUtils.fromJson<ProxyCheckResp>("${account?.proxyDetect}")
                    if(proxyDetect != null){
                        if(!proxyDetect.countryCode.isNullOrEmpty()){
                            AppDivider(modifier = Modifier.padding(vertical = 10.dp))
                            DetailRow(label = "代理国家", value = "${countryNameZh(proxyDetect.countryCode)}\u3000${proxyDetect.city}", copyable = false)
                        }
                        if(!proxyDetect.ip.isNullOrEmpty()){
                            AppDivider(modifier = Modifier.padding(vertical = 10.dp))
                            DetailRow(label = "代理IP", value = "${proxyDetect.ip}", copyable = false)
                        }
                    }
                    VSpacer(12.dp)
                }
            }
        }

        // 底部固定操作栏
        Box(
            modifier = Modifier
                .shadow(4.dp)
                .background(Color.White)
                .padding(start = 12.dp, end = 12.dp, top = 10.dp, bottom = 10.dp + navigationBarHeight)
        ) {
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .shadow(2.dp, RoundedCornerShape(12.dp), clip = true)
                    .background(color = Color.White, RoundedCornerShape(12.dp)),
                verticalAlignment = Alignment.CenterVertically
            ) {
                ActionBottomItem("编辑", R.mipmap.ic_home_bottom_edit, Modifier.weight(1f), account != null) {
                    account?.let { Navigator3.navigate(EditAccountKey(it)) }
                }
                ActionBottomItem("删除", R.mipmap.ic_home_bottom_delete, Modifier.weight(1f), account != null) {
                    account?.let { viewModel.onDeleteAccount(listOf(it)){Navigator3.pop()} }
                }
                ActionBottomItem("检测", R.mipmap.ic_home_bottom_check, Modifier.weight(1f), account != null) {
                    account?.let {
                        viewModel.onCheckAccount(listOf(it)) { account = it }
                    }
                }
                if(account?.twoFa != null)
                    ActionBottomItem("2FA", R.mipmap.ic_home_bottom_auth, Modifier.weight(1f), true) {
                        Navigator3.navigate(Verify2faKey(account))
                    }
                ActionBottomItem("登录", R.mipmap.ic_home_bottom_login, Modifier.weight(1f), account != null) {
                    account?.let {
                        val permissions = arrayListOf(
                            PermissionLists.getBindAccessibilityServicePermission(
                                AppAccessibilityService::class.java),
                            PermissionLists.getBindVpnServicePermission(),
                            PermissionLists.getSystemAlertWindowPermission()
                        )
                        PermissionUtils.requestPermissions(permissions) {
                            Logger.d("获取完权限，开始自动登录")
                        }
                    }
                }
            }
        }
    }
}

@Composable
private fun DetailRow(
    label: String,
    value: String,
    multiLine: Boolean = false,
    copyable: Boolean = false,
    onCopy: (() -> Unit)? = null,
) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .padding(vertical = if (multiLine) 8.dp else 6.dp),
        verticalAlignment = if (multiLine) Alignment.Top else Alignment.CenterVertically,
        horizontalArrangement = Arrangement.SpaceBetween
    ) {
        AppText(text = label, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.then(if (multiLine) Modifier.width(60.dp) else Modifier.width(60.dp)))
        Row(
            verticalAlignment = if (multiLine) Alignment.Top else Alignment.CenterVertically,
        ) {
            if (multiLine) {
                Column(modifier = Modifier.debouncedClickable { onCopy?.invoke() }) {
                    Text(
                        text = value.ifEmpty { "-" },
                        style = MaterialTheme.typography.bodySmall.copy(fontWeight = FontWeight.Bold),
                        color = MaterialTheme.colorScheme.onSurface,
                    )
                }
            } else {
                AppText(
                    text = value.ifEmpty { "-" },
                    style = MaterialTheme.typography.bodySmall.copy(fontWeight = FontWeight.Bold),
                    color = MaterialTheme.colorScheme.onSurface,
                    modifier = Modifier
                )
            }
            if (copyable) {
                HSpacer(6.dp)
                Icon(
                    painter = painterResource(id = R.mipmap.ic_copy_account),
                    contentDescription = "复制",
                    tint = MaterialTheme.colorScheme.onSurfaceVariant,
                    modifier = Modifier
                        .height(18.dp)
                        .debouncedClickable { onCopy?.invoke() }
                )
            }
        }
    }
}